package com.bbx.taxi.client.Activity.Wallet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import butterknife.Bind;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.msg.CouponMsg;
import com.bbx.api.sdk.model.passanger.Coupon;
import com.bbx.api.sdk.model.passanger.Return.Coupon.CouponList;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Coupons;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Metadata.CarClass;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.CouponNet;
import com.bbx.taxi.client.Activity.Menu.ClauseActivity;
import com.bbx.taxi.client.Activity.Wallet.ShareCouponActivity;
import com.bbx.taxi.client.Bean.Extra.ShareCouponMsg;
import com.bbx.taxi.client.Bean.Wallect;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.Util.ToCity2;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.CouponAdapter;
import com.bbx.taxi.client.Bean.Extra.ClauseMsg;
import com.bbx.taxi.client.DB.CouponDB;
import com.bbx.taxi.client.DB.LineDB;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnSwipeListener;

public class CouponActivity extends BaseBBXActivity implements CouponMsg,
		OnLoadListener, OnRefreshListener {
	@Bind(R.id.MyListView)
	MyListView mMyListView;
	@Bind(R.id.pullToRefreshLayout)
	PullToRefreshLayout pullToRefreshLayout;
	@Bind(R.id.layout_nodata)
	LinearLayout layout_nodata;
	private CouponAdapter mCouponAdapter;
	private List<Coupons> list;
	private int start_id = 0;
	/** 加载跟刷新的数量 */
	private int num = -1;
	private CouponDB db_coupon;// 优惠劵数据库
	private Handler handler = new Handler();
	private CouponTask mCouponTask;
	private LineDB db_line;// 线路数据库

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_coupon);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initView() {
		setTitle(true, getString(R.string.coupon_title), -1,
				getString(R.string.coupon_rule));
		db_line = new LineDB();
		db_coupon = new CouponDB();
		initMyListView();
		initswipe();
		list = new ArrayList<Coupons>();
		mCouponAdapter = new CouponAdapter(this, list);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View headerview = inflater.inflate(R.layout.headerview, null);
		// 【主要，添加headerview，则在OnItenClick中的Position就会错乱】
		mMyListView.addHeaderView(headerview, null, false);
		mMyListView.setAdapter(mCouponAdapter);
		onReadDB();
	}

	@Override
	protected void initData() {
	}

	@Override
	public void initswipe() {
		mMyListView.setOnSwipeListener(new OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				pullToRefreshLayout.setIsProhibitPull(true);
			}

			@Override
			public void onSwipeEnd(int position) {
				pullToRefreshLayout.setIsProhibitPull(false);
			}
		});
	}

	private void initMyListView() {
		pullToRefreshLayout.setOnRefreshListener(this);
		mMyListView.setOnLoadListener(this);
		mMyListView.setEmptyView(layout_nodata);
		mMyListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				int headerViewsCount = mMyListView
						.getHeaderViewsCount();// 得到header的总数量
				// 【得到新的修正后的position】
				int newPosition = position - headerViewsCount;
				//等于1的时候才是可分享
				if (list.get(newPosition).getState() == 1) {
					context.startActivityForResult(new Intent(context,
									ShareCouponActivity.class).putExtra(
									ShareCouponMsg.extra_couponid, list.get(newPosition).getId() + ""),
							requestCode);
					//取消所有的红点
					Wallect.isClickShareCoupon = true;
				}

			}
		});
	}

	private void refresh() {
		start_id = 0;
		getCoupon(0);
	}

	private void load() {
		getCoupon(1);
	}

	/**
	 * 获取优惠劵
	 */
	private void getCoupon(int type) {
		Coupon mCoupon = new Coupon(context);
		mCoupon.uid = mApplication.getUid();
		mCoupon.access_token = mApplication.getToken();
		mCoupon.startid = start_id + "";
		mCoupon.num = num + "";
		mCouponTask = new CouponTask(context, mCoupon, type);
		mCouponTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private class CouponTask extends BaseAsyncTask {

		private Coupon mCoupon;
		private int type;// 0为刷新，1为加载

		public CouponTask(Activity context, Coupon mCoupon, int type) {
			super(context, false);
			this.mCoupon = mCoupon;
			setType(type);
			setIsReturnString(true);
		}

		@Override
		public void onSuccess(int status, Object object) {
			if (object != null) {
				CouponList mCouponList = new CouponList();
				JSONArray ja_CouponList;
				try {
					List<Coupons> coupons_list = new ArrayList<Coupons>();
					JSONObject json = new JSONObject((String) object);
					ja_CouponList = json.getJSONArray(msg_coupons);
					for (int i = 0; i < ja_CouponList.length(); i++) {
						Coupons mCoupons = new Coupons();
						JSONObject jo = new JSONObject(ja_CouponList.get(i)
								.toString());
						try {
							mCoupons.setId(Integer.parseInt(jo
									.getString(msg_id)));
						} catch (Exception e) {
						}
						try {
							mCoupons.setState(Integer.parseInt(jo
									.getString(msg_state)));
						} catch (Exception e) {
						}
						try {
							mCoupons.setSum(Integer.parseInt(jo
									.getString(msg_sum)));
						} catch (Exception e) {
						}
						try {
							mCoupons.setTag(jo.getString(msg_tag));
						} catch (Exception e) {
						}
						try {
							mCoupons.setType(Integer.parseInt(jo
									.getString(msg_type)));
						} catch (Exception e) {
						}
						//过期时间
						try {
							mCoupons.setExpire_time(jo
									.getString(msg_expire_time));
						} catch (Exception e) {
						}
						//起始时间
						try {
							mCoupons.setEnable_time(jo
									.getString(CouponMsg.msg_enable_time));
						} catch (Exception e) {
						}
						try {
							mCoupons.setUseLimit(jo.getString(mgs_use_limit));
						} catch (Exception e) {
						}
						//赠送者
						try {
							mCoupons.setGifter(jo.getString(mgs_gifter));
						} catch (Exception e) {
						}
						//赠送时间
						try {
							mCoupons.setGift_time(jo.getString(mgs_gift_time));
						} catch (Exception e) {
						}
						try {
							JSONObject jo_metadata = new JSONObject(
									jo.getString(msg_metadata));
							Metadata mMetadata = new Metadata();
							try {
								JSONArray ja_line = new JSONArray(
										jo_metadata.getString(msg_usableline));
								List<String> list_line = new ArrayList<String>();
								for (int j = 0; j < ja_line.length(); j++) {
									String str_line = ja_line.get(j).toString();
									list_line.add(str_line);
								}
								mMetadata.setUsableline(list_line);
							} catch (Exception e) {
								List<String> list_line = new ArrayList<String>();
								list_line.add(jo_metadata
										.getString(msg_usableline));
								mMetadata.setUsableline(list_line);
							}

							try {
								mMetadata.setUsabletype(jo_metadata
										.getString(msg_usabletype));
							} catch (Exception e) {
							}
							try {
								mMetadata.setUsableorder(jo_metadata
										.getString(msg_usableorder));
							} catch (Exception e) {
							}
							try {
								mMetadata.setUsabletime(jo_metadata
										.getString(msg_usabletime));
							} catch (Exception e) {
							}
							try {
								mMetadata.setPaymode(jo_metadata
										.getString(msg_paymode));
							} catch (Exception e) {
							}
							try {
								mMetadata.setSum_low_limit(jo_metadata
										.getString(msg_sum_low));
							} catch (Exception e) {
							}
							try {
								mMetadata.setBusinessType(jo_metadata
										.getString(mgs_business_type));
							} catch (Exception e) {
							}
							//车型
							try {
								JSONArray ja_car = new JSONArray(
										jo_metadata.getString(mgs_car_class));
								List<CarClass> list_car = new ArrayList<CarClass>();
								if(ja_car.toString().contains("*")){
									CarClass carclass=new Metadata().new CarClass();
									carclass.setName("*");
									list_car.add(carclass);
								}else{
									for (int j = 0; j < ja_car.length(); j++) {
										JSONObject jo_car = new JSONObject(ja_car.get(j).toString());
										CarClass carclass=new Metadata().new CarClass();
										carclass.setId(jo_car.getString(mgs_car_id));
										carclass.setName(jo_car.getString(mgs_car_name));
										list_car.add(carclass);
									}
								}
								mMetadata.setCarClass(list_car);
							
							} catch (Exception e) {
							}
							// //周几限制
							// try {
							// JSONArray ja_time_limit = new JSONArray(
							// jo_metadata.getString(msg_time_week_use));
							// List<String> list_time_limit = new
							// ArrayList<String>();
							// for (int j = 0; j < ja_time_limit.length(); j++)
							// {
							// String str_time_limit =
							// ja_time_limit.get(j).toString();
							// list_time_limit.add(str_time_limit);
							// }
							// mMetadata.time_week_use=list_time_limit;
							// } catch (Exception e) {
							// }
							// //特殊限制，如周几到周几
							// try{
							// JSONObject json_special = new
							// JSONObject(jo_metadata.getString(msg_special_time_nouse));
							// SpecialTime mSpecialTime=new SpecialTime();
							// mSpecialTime.start_time=json_special.getLong(msg_start_time);
							// mSpecialTime.end_time=json_special.getLong(msg_end_time);
							// mMetadata.special_time_nouse=mSpecialTime;
							// }catch(Exception e){}
							mCoupons.setMetadata(mMetadata);
						} catch (Exception e) {
						}
						coupons_list.add(mCoupons);
					}
					mCouponList.setCouponList(coupons_list);
				} catch (JSONException e) {
				}

				if (getType() == 0) {// 刷新
					list.clear();
					int size = 0;
					pullToRefreshLayout
							.refreshFinish(PullToRefreshLayout.SUCCEED);
					if (mCouponList.getCouponList() != null
							&& !mCouponList.getCouponList().isEmpty()) {
						list.addAll(mCouponList.getCouponList());
						// start_id =getStarId(list);
						start_id = mCouponList.getCouponList()
								.get(mCouponList.getCouponList().size() - 1)
								.getId() + 1;
						db_coupon.onDelete();
						db_coupon.onWriteDB(list);
						size = mCouponList.getCouponList().size();
						setLine_CN();
					} else {
						notifyDataSetChanged(mCouponAdapter, 0);
						onDeleteDB();
					}

					if (loaddialog != null) {
						loaddialog.onDismiss();
					}
				} else if (getType() == 1) {// 加载
					// list.clear();
					int size = 0;
					if (mCouponList.getCouponList() != null
							&& !mCouponList.getCouponList().isEmpty()) {
						size = mCouponList.getCouponList().size();
						list.addAll(mCouponList.getCouponList());
						// start_id =getStarId(list);
						start_id = mCouponList.getCouponList()
								.get(mCouponList.getCouponList().size() - 1)
								.getId() + 1;
						// db_coupon.onWriteDB(list);
						size = mCouponList.getCouponList().size();
						mMyListView.setHasMoreData(true);
						setLine_CN();
					} else {
						mMyListView.setHasMoreData(false);
						ToastUtil.showToast(context, R.string.in_the_end);
					}

				}
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			if (getType() == 0) {// 刷新
				pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
				ToastUtil.showToast(context, R.string.no_network);
			} else if (getType() == 1) {// 加载
				ToastUtil.showToast(context, R.string.load_fail);
			}
			if (loaddialog != null) {
				loaddialog.onDismiss();
			}
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mCoupon).getJson();
			return new CouponNet(context, json);
		}

	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	/**
	 * 刚进来的时候读取的
	 */
	private void onReadDB() {
		new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if (loaddialog != null && !loaddialog.isShowing()) {
					loaddialog.show();
				}
				super.onPreExecute();
			}

			protected Void doInBackground(Void... params) {
				list.clear();
				list.addAll(db_coupon.onReadDB(-1, num));
				return null;

			}

			protected void onPostExecute(Void result) {
				setLine_CN();
				refresh(); // 主动下拉刷新所有的订单
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * 删除所有数据
	 */
	public void onDeleteDB() {
		db_coupon.onDelete();
	}

	protected void onDestroy() {
		if (mCouponTask != null
				&& mCouponTask.getStatus() != AsyncTask.Status.FINISHED)
			mCouponTask.cancel(true);
		super.onDestroy();

	}

	/**
	 * 刷新或加载出几个size
	 */
	public void notifyDataSetChanged(BaseAdapter adapter, int size) {
		for (int i = list.size() - 1; i >= 0; i--) {
			long gift_time=0;
			try{gift_time=Long.parseLong(list.get(i).getGift_time());}catch (Exception e){}
			//先判断没有赠送的跟赠送后的5天前
			 if(list.get(i).getState()==CouponAdapter.state_no_gift
					||(list.get(i).getState()==CouponAdapter.state_gift&&(gift_time*1000)>=
					new Date().getTime() - (5 * 24 * 60 * 60 * 1000))
			     ){
                 // 没有过期的跟5天前的
				 if (((Long.parseLong(list.get(i).getExpire_time()) * 1000) >= new Date()
						 .getTime() - (5 * 24 * 60 * 60 * 1000))
						 || Long.parseLong(list.get(i).getExpire_time()) == 0) {

				 }else{
					 list.remove(i);
				 }
			}
			else {
				list.remove(i);
			}
		}
		// 已赠送
		List<Coupons> list_gifter = new ArrayList<Coupons>();
		// 已赠送,没有过期限制
		List<Coupons> list_gifter2 = new ArrayList<Coupons>();
		// 过期
		List<Coupons> list_expire = new ArrayList<Coupons>();
		// 没有限制
		List<Coupons> list_no = new ArrayList<Coupons>();
		// 有限制的
		List<Coupons> list_has = new ArrayList<Coupons>();
		for (int i = 0; i < list.size(); i++) {
			long expire_time=0;
			try{expire_time=Long.parseLong(list.get(i).getExpire_time());}catch (Exception e){}
			//已赠送
			if(list.get(i).getState()==CouponAdapter.state_gift){
				//没有过期时间限制
				if(expire_time == 0){
					list_gifter2.add(list.get(i));
				}else{
					list_gifter.add(list.get(i));
				}

			}
			//未过期
			else if(expire_time== 0) {
				list_no.add(list.get(i));
			} else {
				if ((expire_time * 1000) >= new Date()
						.getTime()) {
					list_has.add(list.get(i));
				} else {
					list_expire.add(list.get(i));

				}

			}
		}

		// 排序，由于优惠劵默认是是金额排序，所以要在自定义
		// 有时间限制的排序
		class CouponPriceComparator implements Comparator {
			public int compare(Object object1, Object object2) {// 实现接口中的方法
				Coupons p1 = (Coupons) object1; // 强制转换
				Coupons p2 = (Coupons) object2;
				if (p1.getExpire_time().equals(p2.getExpire_time())) {
					return p2.getSum().compareTo(p1.getSum());
				}
				return new Long(p1.getExpire_time()).compareTo(new Long(p2
						.getExpire_time()));
			}
		}
		// 没有有时间限制的排序
		class NoComparator implements Comparator {
			public int compare(Object object1, Object object2) {// 实现接口中的方法
				Coupons p1 = (Coupons) object1; // 强制转换
				Coupons p2 = (Coupons) object2;
				return p2.getSum().compareTo(p1.getSum());
			}
		}
		// 有时间限制的排序
		class expireCouponPriceComparator implements Comparator {
			public int compare(Object object1, Object object2) {// 实现接口中的方法
				Coupons p1 = (Coupons) object1; // 强制转换
				Coupons p2 = (Coupons) object2;
				if (p1.getExpire_time().equals(p2.getExpire_time())) {
					return p2.getSum().compareTo(p1.getSum());
				}
				return new Long(p1.getExpire_time()).compareTo(new Long(p2
						.getExpire_time()));
			}
		}
		Collections.sort(list_has, new CouponPriceComparator());
		Collections.sort(list_no, new NoComparator());
		Collections.sort(list_expire, new expireCouponPriceComparator());
		Collections.sort(list_gifter, new expireCouponPriceComparator());
		Collections.sort(list_gifter2, new expireCouponPriceComparator());
		list.clear();
		list.addAll(list_has);
		list.addAll(list_no);
		list.addAll(list_gifter);
		list.addAll(list_gifter2);
		list.addAll(list_expire);
		adapter.notifyDataSetChanged();
		onisShowNodata(adapter);
	}

	public void onisShowNodata(BaseAdapter adapter) {
		// if (adapter.getCount() == 0) {
		// layout_nodata.setVisibility(View.VISIBLE);
		// } else {
		// layout_nodata.setVisibility(View.GONE);
		// }
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:
			startActivity(new Intent(this, ClauseActivity.class).putExtra(
					ClauseMsg.extra_clause, ClauseMsg.CLAUSE_COUPON));
			break;
		default:
			super.onClick(v);
			break;
		}

	}

	public int getStarId(List<Coupons> list) {
		int start_id = 0;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getId() > start_id) {
				start_id = list.get(i).getId();
			}
		}
		// 最后一定要+1，用于拉取下一段数据开始的id
		return start_id + 1;

	}

	/**
	 * 刷新或加载出几个Size
	 */
	public void setLine_CN() {
		new AsyncTask<Void, Void, Void>() {
			//城际
			List<String> list_line_num=new ArrayList<String>();
			List<String> list_line_cn=new ArrayList<String>();
			//市内
			List<String> list_incity_num=new ArrayList<String>();
			List<String> list_incity_cn=new ArrayList<String>();
			@Override
			protected Void doInBackground(Void... arg0) {
				list_line_num.addAll(ToCity2.getListLineId(false));
				list_line_cn.addAll(ToCity2.getListLineName(false));
				list_incity_num.addAll(ToCity2.getListLineId(true));
				list_incity_cn.addAll(ToCity2.getListLineName(true));
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				for (int z = 0; z < list.size(); z++) {
					String name;
					if (list.get(z).getMetadata() != null) {
						List<String> list_line = list.get(z).getMetadata()
								.getUsableline();
						if (list_line != null) {
							String line = "";
							for (int i = 0; i < list_line.size(); i++) {
								if (list_line.get(i).trim().equals("*")
										|| list_line.get(i).trim().equals("\"*\"")
										|| list_line.get(i).trim().equals("\"[*]\"")) {
									int type = 0;
									try {
										type = Integer.parseInt(list.get(z)
												.getMetadata().getUsabletype());
									} catch (Exception e) {
									}
									line = getString(R.string.line_name_all);
									//暂时屏蔽
//							// 适用于全部
//							if (type == -1) {
//								line = getString(R.string.line_name_all);
//							}
//							// 适用于所有市内
//							else if ((type & CouponAdapter.int_type[0]) > 0) {
//								line = getString(R.string.line_name_all_sn);
//							} else {
//								line = getString(R.string.line_name_all_cj);
//							}

									break;
								} else {
									// 城际
									for (int j = 0; j < list_line_num.size(); j++) {
										if (list_line.get(i).trim()
												.equals(list_line_num.get(j).trim())) {
											if (i != 0 && list_line.size() != 1) {
												line += "、";
											}
											line = line + list_line_cn.get(j);
											break;
										}
									}
									// 市内
									for (int j = 0; j < list_incity_num.size(); j++) {
										if (list_line.get(i).trim()
												.equals(list_incity_num.get(j).trim())) {
											if (i != 0 && list_line.size() != 1) {
												line += "、";
											}
											line = line + list_incity_cn.get(j) + "内";
											break;
										}
									}

								}
							}
							// 去掉、开头的字，如“、厦门到漳州”
							if (line.startsWith("、")) {
								if (line.length() > 1) {
									line = line.substring(1, line.length());
								}
							}
							// 获取不到线路，则默认全部路线
							if (line.equals("")) {
								name = "";
							} else {
								name = String.format(getString(R.string.line_name),
										line);
							}
							list.get(z).setLine_CN(name);
						}
					}
				}

				for (int i = list.size() - 1; i >= 0; i--) {
					if (list.get(i).getLine_CN() == null) {
						list.remove(i);
					} else if (list.get(i).getLine_CN() != null
							&& list.get(i).getLine_CN().equals("")) {
						list.remove(i);
					}
				}

				notifyDataSetChanged(mCouponAdapter, list.size());
				super.onPostExecute(result);
			}
		}.execute();
	}

	@Override
	public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
		refresh();
	}

	@Override
	public void onLoad(PullableListView pullableListView) {
		load();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(this.requestCode==requestCode&&this.resultCode==resultCode){
			refresh();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
